import { PageContainer } from "@ant-design/pro-components";
import {
  Avatar,
  Button,
  Card,
  Col,
  message,
  Row,
  Descriptions,
  Divider,
  Tabs,
  Image,
  Tag,
  Popconfirm,
  Spin,
  List,
  Radio,
  Space,
  Typography,
} from "antd";
import { useEffect, useRef, useState } from "react";
import {
  PlayCircleOutlined,
  PictureOutlined,
  DeleteOutlined,
  VideoCameraOutlined,
  StarOutlined,
  ManOutlined,
  WomanOutlined,
  RotateLeftOutlined,
  RotateRightOutlined,
  ZoomInOutlined,
  ZoomOutOutlined,
  RedoOutlined,
} from "@ant-design/icons";
import FaceInputForm from "./components/FaceInputForm";
import {
  deleteFacec,
  faceLibraryList,
  getFaceDetail,
  updateMatches,
} from "@/services/api/api-face-library";
import ImageViewer from "@/components/ImageViewr";
import VideoViewer from "@/components/VideoView";

const { TabPane } = Tabs;
const { Text } = Typography;

interface OriginalImage {
  folder_id: number;
  folder_path: string;
  url: string;
}

interface UserItem {
  id: string;
  name: string;
  thumbnail_url: string;
  gender: string;
  face_group_id?: string;
  type?: "all" | "black" | "white";
}

interface FaceDetail {
  face_id: string;
  id: string;
  name: string;
  avatar: string;
  gender: string;
  age: number;
  description: string;
  media?: MediaItem[];
  type?: string;
  face_info: {
    gender: string;
    age: number;
    name: string;
    type?: "all" | "black" | "white";
    description: string;
  };
  original_images?: OriginalImage[];
  video_clips?: VideoClip[];
  highlights?: Highlight[];
  list_type?: "all" | "black" | "white";
}

interface MediaItem {
  id: string;
  name: string;
  type: "image" | "video";
  url: string;
  timestamp: string;
}

interface VideoClip {
  clip_url: string;
  end_time?: number;
}

interface Highlight {
  highlight_url: string;
  created_at?: string;
}

const ComparisonLibrary: React.FC = () => {
  const [listData, setListData] = useState<UserItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [page, setPage] = useState(1);
  const [columns, setColumns] = useState(4);
  const [selectedFace, setSelectedFace] =
    useState<ProcessingData.detailRecord | null>(null);
  const [selectedFaceId, setSelectedFaceId] = useState<string | null>(null);
  const [detailLoading, setDetailLoading] = useState(false);
  const [deleting, setDeleting] = useState(false);
  const [activeTab, setActiveTab] = useState("1");
  const [listType, setListType] = useState<"all" | "black" | "white">("all");
  const [updating, setUpdating] = useState(false); // 新增：更新加载状态
  const containerRef = useRef<HTMLDivElement>(null);

  const CONTAINER_HEIGHT = 700;
  const CARD_WIDTH = 130;
  const CARD_GAP = 16;

  const calculateColumns = () => {
    if (!containerRef.current) return 4;
    const containerWidth = containerRef.current.clientWidth;
    return Math.max(1, Math.floor(containerWidth / (CARD_WIDTH + CARD_GAP)));
  };

  const loadListData = async (reset = false) => {
    if (loading) return;
    setLoading(true);

    try {
      const currentColumns = calculateColumns();
      const loadCount = currentColumns * 4;
      const targetPage = reset ? 1 : page;

      const res = await faceLibraryList({
        type: listType,
        currentPage: targetPage,
        pageSize: loadCount,
      });

      const newData = res.data.data;
      setListData((prev) => (reset ? newData : [...prev, ...newData]));
      setPage(targetPage + 1);

      if (reset) {
        setSelectedFaceId(null);
        setSelectedFace(null);
      }

      if (
        selectedFaceId &&
        !newData.some((item) => item.id === selectedFaceId)
      ) {
        setSelectedFaceId(null);
        setSelectedFace(null);
      }
    } catch (err) {
      message.error("数据加载失败");
    } finally {
      setLoading(false);
    }
  };

  const fetchFaceDetail = async (id: string) => {
    setDetailLoading(true);
    try {
      const res = await getFaceDetail({
        face_id: id,
        currentPage: 1,
        pageSize: 10,
      });

      setSelectedFace(res.data);
      setSelectedFaceId(id);
    } catch (err) {
      message.error("获取详情失败");
      setSelectedFaceId(null);
    } finally {
      setDetailLoading(false);
    }
  };

  const handleDelete = async (id: string) => {
    setDeleting(true);
    try {
      await deleteFacec(Number(id));

      setListData((prev) => prev.filter((item) => item.id !== id));

      if (selectedFaceId === id) {
        setSelectedFaceId(null);
        setSelectedFace(null);
      }

      message.success("删除成功");
    } catch (error) {
      message.error("删除失败");
    } finally {
      setDeleting(false);
    }
  };

  const handleCardClick = (user: UserItem) => {
    fetchFaceDetail(user.id);
  };

  const handleInputSuccess = () => {
    loadListData(true);
    // message.success("人脸信息已更新");
  };

  const handleListTypeChange = (e: any) => {
    setListType(e.target.value);
    setSelectedFaceId(null);
    setSelectedFace(null);
  };

  const handleUpdateLibrary = async () => {
    setUpdating(true);
    try {
      const res = await updateMatches();
      if (res.code === 0) {
        message.success("更新成功");
      }
    } catch (error) {
      message.error("更新失败");
    } finally {
      setUpdating(false);
    }
  };

  useEffect(() => {
    loadListData(true);
  }, [listType]);

  useEffect(() => {
    const container = containerRef.current;
    if (!container) return;

    const handleScroll = () => {
      const { scrollTop, scrollHeight, clientHeight } = container;
      if (scrollHeight - scrollTop <= clientHeight + 50 && !loading) {
        loadListData(); // 滚动加载更多
      }
    };

    container.addEventListener("scroll", handleScroll);
    return () => container.removeEventListener("scroll", handleScroll);
  }, [loading, columns]);

  const renderDetailContent = () => {
    if (detailLoading) {
      return (
        <div
          style={{
            height: CONTAINER_HEIGHT,
            display: "flex",
            justifyContent: "center",
            alignItems: "center",
          }}
        >
          <Spin tip="加载详情中..." />
        </div>
      );
    }

    if (!selectedFace) {
      return (
        <div
          style={{
            height: CONTAINER_HEIGHT,
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            border: "1px dashed #d9d9d9",
            borderRadius: 8,
            background: "#fafafa",
          }}
        >
          <div style={{ textAlign: "center", color: "#999" }}>
            <p>请从左侧选择一个人物查看详细信息</p>
          </div>
        </div>
      );
    }

    return (
      <Card
        title="详细信息"
        style={{ height: CONTAINER_HEIGHT, overflow: "auto" }}
        extra={[
          <Popconfirm
            key="delete"
            title="确定要删除这个人脸信息吗？"
            onConfirm={() => handleDelete(selectedFace.face_id)}
            okText="确定"
            cancelText="取消"
          >
            <Button danger icon={<DeleteOutlined />} loading={deleting}>
              删除
            </Button>
          </Popconfirm>,
        ]}
      >
        <div
          style={{
            display: "flex",
            gap: "20px",
            padding: 20,
            backgroundColor: "#fff",
            borderRadius: 12,
            boxShadow: "0 2px 12px rgba(0, 0, 0, 0.08)",
          }}
        >
          <div
            style={{
              display: "flex",
              flexDirection: "column",
              alignItems: "center",
              paddingRight: 20,
              borderRight: "1px dashed #e8e8e8",
            }}
          >
            <Image
              src={selectedFace.thumbnail_url}
              style={{
                width: 100,
                height: 100,
                borderRadius: "50%",
                objectFit: "cover",
                padding: 10,
              }}
            />
            <Tag
              color={
                selectedFace.face_info.type === "black"
                  ? "error"
                  : selectedFace.face_info.type === "white"
                  ? "success"
                  : "processing"
              }
              style={{
                fontWeight: "bold",
                borderRadius: 16,
                padding: "4px 12px",
              }}
            >
              {selectedFace.face_info.type === "black"
                ? "黑名单"
                : selectedFace.face_info.type === "white"
                ? "白名单"
                : "普通"}
            </Tag>
          </div>

          <div style={{ flex: 1 }}>
            <div style={{ marginBottom: 12 }}>
              <span
                style={{ fontWeight: "bold", color: "#666", marginRight: 8 }}
              >
                姓名:
              </span>
              <span style={{ fontSize: "16px", fontWeight: 500 }}>
                {selectedFace.face_info.name}
              </span>
            </div>

            <div
              style={{
                backgroundColor: "#f9f9f9",
                padding: 12,
                borderRadius: 6,
                borderLeft: "3px solid #1890ff",
              }}
            >
              <div
                style={{ fontWeight: "bold", color: "#666", marginBottom: 4 }}
              >
                描述:
              </div>
              <div
                style={{
                  color: selectedFace.face_info.description ? "#333" : "#999",
                  lineHeight: 1.5,
                }}
              >
                {selectedFace.face_info.description || "暂无描述"}
              </div>
            </div>
          </div>
        </div>

        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <TabPane
            tab={
              <span>
                <PictureOutlined />
                原始图片
              </span>
            }
            key="1"
          >
            <div style={{ marginBottom: 24 }}>
              {selectedFace.original_images?.length ? (
                <List
                  grid={{ gutter: 16, column: 2 }}
                  dataSource={selectedFace.original_images}
                  renderItem={(image, index) => (
                    <List.Item>
                      <Card
                        size="small"
                        title={`原始图片 ${index + 1}`}
                        extra={
                          image.positions && (
                            <Tag color="blue">已检测到人脸</Tag>
                          )
                        }
                      >
                        <ImageViewer
                          imageUrl={image.url}
                          position={image.positions[0]}
                          similarity={image.similarity}
                        />
                        <div style={{ marginTop: 12 }}>
                          <Text ellipsis style={{ width: "100%" }}>
                            路径: {image.folder_path}
                          </Text>
                        </div>
                      </Card>
                    </List.Item>
                  )}
                />
              ) : (
                <div style={{ textAlign: "center", padding: 24 }}>
                  <p>暂无原始图片</p>
                </div>
              )}
            </div>
          </TabPane>
          <TabPane
            tab={
              <span>
                <VideoCameraOutlined />
                视频片段
              </span>
            }
            key="2"
          >
            <div style={{ marginBottom: 24 }}>
              {selectedFace.video_clips?.length ? (
                <List
                  grid={{ gutter: 16, column: 1 }}
                  dataSource={selectedFace.video_clips}
                  renderItem={(clip, index) => {
                    // 使用可选链和空值合并确保安全访问
                    const endTime = clip?.end_time ?? null;
                    const startTime = clip?.start_time ?? null;

                    const clipDuration =
                      endTime !== null &&
                      startTime !== null &&
                      typeof endTime === "number" &&
                      typeof startTime === "number"
                        ? endTime - startTime
                        : undefined;
                    console.log(clipDuration, clip.end_time, clip.start_time);

                    return (
                      <List.Item>
                        <Card
                          title={`视频片段 ${index + 1}`}
                          extra={
                            <span>
                              时长:{" "}
                              {clipDuration
                                ? clipDuration.toFixed(1) + "s"
                                : "N/A"}
                            </span>
                          }
                        >
                          <VideoViewer
                            videoUrl={clip.clip_url}
                            positions={clip.positions}
                            startTime={clip.start_time}
                            endTime={clip.end_time}
                            clipDuration={clipDuration}
                            style={{ maxWidth: "100%" }}
                          />
                        </Card>
                      </List.Item>
                    );
                  }}
                />
              ) : (
                <div style={{ textAlign: "center", padding: 24 }}>
                  <p>暂无视频片段</p>
                </div>
              )}
            </div>
          </TabPane>
          <TabPane
            tab={
              <span>
                <StarOutlined />
                集锦
              </span>
            }
            key="3"
          >
            <div style={{ marginBottom: 24 }}>
              {selectedFace.highlights?.length ? (
                <List
                  grid={{ gutter: 16, column: 2 }}
                  dataSource={selectedFace.highlights}
                  renderItem={(clip, index) => (
                    <List.Item>
                      <Card
                        title={`集锦片段 ${index + 1}`}
                        extra={<span>{clip?.created_at}</span>}
                      >
                        <video
                          width="100%"
                          style={{ maxHeight: 300 }}
                          controls
                          src={clip?.highlight_url ?? ""}
                        />
                      </Card>
                    </List.Item>
                  )}
                />
              ) : (
                <div style={{ textAlign: "center", padding: 24 }}>
                  <p>暂无集锦片段</p>
                </div>
              )}
            </div>
          </TabPane>
        </Tabs>
      </Card>
    );
  };

  return (
    <PageContainer
      header={{
        title: "人脸库",
        breadcrumb: {},
      }}
      extra={[
        <FaceInputForm key="input-form" onSuccess={handleInputSuccess} />,
      ]}
    >
      <Row gutter={16}>
        <Col span={12}>
          <div
            style={{
              marginBottom: 16,
              display: "flex",
              justifyContent: "space-between",
            }}
          >
            <Radio.Group onChange={handleListTypeChange} value={listType}>
              <Radio.Button value="all">全部</Radio.Button>
              <Radio.Button value="white">白名单</Radio.Button>
              <Radio.Button value="black">黑名单</Radio.Button>
            </Radio.Group>
            <Button
              type="primary"
              onClick={handleUpdateLibrary}
              loading={updating}
              icon={updating ? <Spin size="small" /> : null}
            >
              {updating ? "更新中..." : "更新"}
            </Button>
          </div>

          <div
            ref={containerRef}
            style={{
              height: CONTAINER_HEIGHT,
              overflow: "auto",
              padding: "8px",
              border: "1px solid #f0f0f0",
              borderRadius: "8px",
            }}
          >
            <div
              style={{
                display: "grid",
                gridTemplateColumns: `repeat(auto-fill, ${CARD_WIDTH}px)`,
                justifyContent: "space-between",
                gap: `${CARD_GAP}px`,
                paddingBottom: "40px",
              }}
            >
              {listData.map((item) => (
                <Card
                  hoverable
                  key={item.id}
                  style={{
                    width: CARD_WIDTH,
                    height: 160,
                    border:
                      selectedFaceId === item.id
                        ? "2px solid #1890ff"
                        : "1px solid #f0f0f0",
                    boxShadow:
                      selectedFaceId === item.id
                        ? "0 2px 8px rgba(24, 144, 255, 0.2)"
                        : "none",
                  }}
                  onClick={() => handleCardClick(item)}
                  cover={
                    <Avatar
                      src={item.thumbnail_url}
                      style={{
                        height: 120,
                        width: "100%",
                        objectFit: "cover",
                        opacity: selectedFaceId === item.id ? 0.9 : 1,
                      }}
                    />
                  }
                >
                  <div
                    style={{
                      display: "flex",
                      justifyContent: "space-between",
                      alignItems: "center",
                      gap: "6px", // 使用gap控制间距
                      margin: "-15px -10px",
                    }}
                  >
                    <span
                      style={{
                        color:
                          selectedFaceId === item.id ? "#1890ff" : "#1f1f1f",
                        fontSize: "13px",
                        lineHeight: "1.2",
                        flex: 1,
                        overflow: "hidden",
                        textOverflow: "ellipsis",
                        whiteSpace: "nowrap",
                      }}
                    >
                      {item.name}
                    </span>
                    <Tag
                      color={
                        item.type === "black"
                          ? "red"
                          : item.type === "white"
                          ? "green"
                          : "default"
                      }
                    >
                      {item.type === "black"
                        ? "黑名单"
                        : item.type === "white"
                        ? "白名单"
                        : "普通"}
                    </Tag>
                  </div>
                </Card>
              ))}
            </div>

            {loading && (
              <div style={{ textAlign: "center", padding: 16 }}>
                <Spin tip="加载中..." />
              </div>
            )}
          </div>
        </Col>

        <Col span={12}>{renderDetailContent()}</Col>
      </Row>
    </PageContainer>
  );
};

export default ComparisonLibrary;
